package str

import (
	"encoding/json"
	"fmt"
	"sort"
)

func GenInsertSql(data map[string]interface{}, jsonData map[string]interface{}, table string) map[string]interface{} {
	head := "insert into " + table + " ("
	body := "\n("
	var keys = make([]string, 0, 1000)
	for key := range jsonData {
		keys = append(keys, key)
	}
	sort.Strings(keys)
	for _, field := range keys {
		value := jsonData[field]
		head += field + ", "
		switch value.(type) {
		case int, int64:
			body += fmt.Sprintf("%d", value) + ", "
		case float32, float64:
			body += fmt.Sprintf("%f", value) + ", "
		case nil:
			body += "NULL, "
		case string:
			body += "'" + value.(string) + "', "
		case map[string]string, []interface{}, map[string]interface{}:
			stc, _ := json.Marshal(value)
			body += "'" + string(stc) + "', "
		default:
			fmt.Print("str.GenInsertSql, default: ", value, " ")
			panic("未知的数据类型")
		}
	}
	head_r := []rune(head)
	head_r = head_r[:len(head_r)-2]
	head = string(head_r) + ")"
	body_r := []rune(body)
	body_r = body_r[:len(body_r)-2]
	body = string(body_r) + ")"
	data_len, _ := data["len"].(int)
	data_sql, _ := data["sql"].([]string)
	if 0 == data_len%1000 {
		sql := head + " values " + body
		data_sql = append(data_sql, sql)
	} else {
		data_sql[len(data_sql)-1] += "," + body
	}
	data["sql"] = data_sql
	data_len += 1
	data["len"] = data_len
	return data
}
